#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout);
#define pb push_back
#define vec vector<int>

int read(){int x = 0,sgn = 1;char ch = getchar();for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);return x*sgn;}

const int N = 1e5+10;

int n,f[N],ans[N],md,dep[N],Q;
int id[N * 30],ls[N * 30],rs[N * 30],a[N],cnt,rt[N],ndn,scnt;
map<string,int> dic;
vector<pii> qes[N];
vector<int> G[N];
set<int> s[N*30];

int newnode(){return ++ndn;}

void insert(int &o,int ps,int v,int l = 1,int r = md){
	if(!o) o = newnode();
	if(l == r) {
		if(!id[o]) id[o] = ++scnt;
		return s[id[o]].insert(v),void();
	}
	int mid = l + r >> 1;
	if(ps <= mid) insert(ls[o],ps,v,l,mid); else insert(rs[o],ps,v,mid + 1,r);
}

void mergeset(int &x,int &y){
	if(s[y].size() > s[x].size()) swap(x,y);
	for(auto t : s[y]) if(s[x].find(t) == s[x].end()) s[x].insert(t); s[y].clear();
}

void merge(int &y,int x,int l = 1,int r = md){
	if(!y || !x) return y = x + y,void();
	if(l == r){
		if(!id[y]) id[y] = id[x];
		else mergeset(id[y],id[x]);
		return;
	}
	int mid = l + r >> 1;
	merge(ls[y],ls[x],l,mid); merge(rs[y],rs[x],mid+1,r);
}

int query(int o,int ps,int l = 1,int r = md){
	if(l == r) return s[id[o]].size(); int mid = l + r >> 1;
	if(ps <= mid) return query(ls[o],ps,l,mid); else return query(rs[o],ps,mid+1,r);
}

void dfs(int x,int p){
	dep[x] = dep[p] + 1; md = max(md,dep[x]);
	for(auto y : G[x]) dfs(y,x);
	if(x) insert(rt[x],dep[x],a[x]);
	for(auto y : G[x]) merge(rt[x],rt[y]);
	for(auto q : qes[x]){
		int d = dep[x] + q.fi,iid = q.se;
		if(d <= md) ans[iid] = query(rt[x],d);
	}
}

int main (){
#ifndef ONLINE_JUDGE
	freopen("1.in","r",stdin);
#endif
	n = in;
	for(int i = 1;i <= n;i++){
		string na; cin >> na; f[i] = in; if(!dic[na]) dic[na] = ++cnt; 
		G[f[i]].pb(i); a[i] = dic[na];
	}
	Q = in;
	for(int i = 1,x,y;i <= Q;i++) x = in,y = in,qes[x].pb(pii(y,i));
	dfs(0,0);
	for(int i = 1;i <= Q;i++) printf("%d\n",ans[i]);
	return 0;
}
